package com.liwen.test.jdkproxy;

import sun.misc.ProxyGenerator;

import java.io.FileOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * jdk动态代理
 */
public class JdkInvocationHandler implements InvocationHandler {


    private IHello target;

    public Object getInstance(IHello target) {
        this.target = target;
        Class clazz = this.target.getClass();
        // 参数1：被代理类的类加载器 参数2:被代理类的接口 参数3
        return Proxy.newProxyInstance(clazz.getClassLoader(),
                clazz.getInterfaces(),
                this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("before");
        Object o = method.invoke(target, args);
        System.out.println("after");
        return o;
    }

    public static void main(String[] args) {


        IHello hello = new Hello();
        IHello proxy = (IHello) new JdkInvocationHandler().getInstance(hello);
        proxy.sayHello();

        // 这里我们将jdk生成的代理类输出了出来，方便后面分析使用
        byte[] bytes = ProxyGenerator.generateProxyClass("$Proxy0",hello.getClass().getInterfaces());
        try{
            FileOutputStream os = new FileOutputStream("E:\\Proxy0.class");
            os.write(bytes);
            os.close();
        }catch(Exception e){
            e.printStackTrace();
        }



    }


}
